package com.wuda.servlet;

import com.wuda.bean.User;
import com.wuda.dao.UserDao;
import com.wuda.utils.Util;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;


@WebServlet("/login")
public class Login extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf8");
		PrintWriter out = response.getWriter();

		String email = request.getParameter("email");
		String psw = request.getParameter("password");

		String encryptedPsw = Util.passMd5(psw);

		HashMap<String, Object> hashMap = new HashMap<>();

		UserDao userDao = new UserDao();
		User user;
		try {
			user = userDao.findUserByEmail(email);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
			hashMap.put("code", 500);
			hashMap.put("msg", "数据库操作错误");
			JSONObject json = JSONObject.fromObject(hashMap);
			out.write(json.toString());
			return;
		}

		if (user == null) {
			hashMap.put("code", 201);
			hashMap.put("msg", "用户不存在");
		} else if (!user.getPassword().equals(encryptedPsw)) {
			hashMap.put("code", 202);
			hashMap.put("msg", "密码错误");
		} else if (user.getStatus().equals("inactive")) {
			hashMap.put("code", 203);
			hashMap.put("msg", "用户已被禁用");
		} else {
			HttpSession session = request.getSession();

			session.setAttribute("user", user);

			hashMap.put("code", 200);
			hashMap.put("msg", "登录成功");
			hashMap.put("url", request.getContextPath() + "/index.jsp");
		}

		JSONObject json = JSONObject.fromObject(hashMap);
		out.write(json.toString());
	}


}
